package cn.edu.buaa.purain.db;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

@SuppressWarnings("unchecked")
public class ConnectionByXMLProperty implements IConnectionProvider{
	
	private final String property_file = "conf/jdbc.xml";
	private Map<String, DBElement> connMaps = new HashMap<String, DBElement>();
	
	private class DBElement {
		String name;
		String driver;
		String url;
		String username;
		String password;
		@SuppressWarnings("unused")
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getDriver() {
			return driver;
		}
		public void setDriver(String driver) {
			this.driver = driver;
		}
		public String getUrl() {
			return url;
		}
		public void setUrl(String url) {
			this.url = url;
		}
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
	}
	
	public ConnectionByXMLProperty() throws Exception{
		InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(property_file);
		
		if (null == inStream) {
			throw new Exception("Unable to find property file ");
		}
		
		SAXBuilder sax = new SAXBuilder();
		try {
			Document document = sax.build(inStream);
			
			Element root = document.getRootElement();
			
			List<Element> dbs = root.getChildren();
			for (Element e : dbs) {
				String name = e.getChildText("name");
				String driver = e.getChildText("driver");
				String url = e.getChildText("url");
				String username = e.getChildText("username");
				String password = e.getChildText("password");
				
				DBElement ele = new DBElement();
				ele.setName(name);
				ele.setDriver(driver);
				ele.setUrl(url);
				ele.setUsername(username);
				ele.setPassword(password);
				
				connMaps.put(name, ele);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Connection getConnection(String dbName) throws Exception {
		DBElement ele = connMaps.get(dbName);
		
		Class.forName(ele.getDriver());
		return DriverManager.getConnection(ele.getUrl(), ele.getUsername(), ele.getPassword());
	}	

}
